import React from "react";
import {connect} from 'dva';
import {Button, Card, Form, message, Popconfirm, Spin, Table, Tooltip} from "antd";
import EditAccount from "./EditAccount";
import ExportModal from "../ExportModal";
import {PageHeaderWrapper} from "@ant-design/pro-layout";
import FilterForm from "@/components/BaseForm/FilterForm";
import witty from "@/utils/wittyUtils";

let pagingData = {
    _pageSize: 10,
    _current: 1,
    _total: 0,
};

@connect(({accountModel}) => ({
    accountModel,
}))
class Account extends React.Component {
    state = {
        //-- 页面数据
        dataSource: [],
        //-- 加载层
        loading: false,
        //-- [true]: 显示搜索条件, [false]: 隐藏搜索条件
        showMoreSearchForm: false,
        //-- 选中的RowKeys
        selectedRowKeys: [],
        //-- 选中的Rows
        selectedRows: [],
    }

    componentDidMount() {
        //-- 获取表格数据
        this.findPageData();
    }

    /**
     * 查询页面数据
     */
    findPageData = function (params = {}) {
        const thisCtx = this;
        const {dispatch} = this.props;

        if (params.createTime) {
            params.startDate = params.createTime[0].format('YYYY-MM-DD');
            params.endDate = params.createTime[1].format('YYYY-MM-DD');
            delete params.createTime;
        }

        params.currentPage = pagingData._current;
        params.pageSize = pagingData._pageSize;
        console.log(params);
        thisCtx.setState({loading: true});
        dispatch({
            type: 'accountModel/userList',
            payload: params,
            callback: function (data) {
                thisCtx.setState({loading: false});
                if (data && data.success) {
                    const paging = data.datas.pagination;
                    pagingData._current = paging.current + 1;
                    pagingData._pageSize = paging.pageSize;
                    pagingData._total = paging.total;
                    thisCtx.setState({
                        //-- 重置选中的行
                        selectedRowKeys: [],
                        selectedRows: [],
                        dataSource: data.datas.list,
                    });
                } else {
                    message.error('账户信息获取失败');
                }
            }
        });
    }

    /**
     * 显示或者隐藏 [更多搜索条件]
     */
    showOrHideMoreSearchForm = () => {
        const {showMoreSearchForm} = this.state;

        this.setState({
            showMoreSearchForm: !showMoreSearchForm,
        });
    };

    handleFilter = (params) => {
        this.params = params;
        witty.validNilParams(params)
        if (witty.isValidObj(params)) {
            pagingData._current = 1;
            witty.validNilParams(params);
            this.findPageData(params);
        }
    }

    handlerDelAccount = () => {
        const {selectedRowKeys} = this.state;
        if (selectedRowKeys.length == 1) {
            const thisCtx = this;
            const {dispatch} = this.props;
            let params = {};
            params.id = selectedRowKeys[0];
            params.isenabled = -1;
            console.log(params);
            dispatch({
                type: 'accountModel/delUser',
                payload: params,
                callback: function (data) {
                    if (data && data.success) {
                        message.success('数据删除成功');
                        thisCtx.findPageData();
                    } else {
                        message.error('数据删除失败');
                    }
                }
            });
        } else {
            message.info('请选中一行数据');
        }
    }

    formList = [
        {
            type: 'INPUT',
            label: '用户Id',
            field: 'userId',
            placeholder: '请输入用户Id',
        },
        {
            type: 'INPUT',
            label: '手机号',
            field: 'phone',
        },
        {
            type: 'INPUT',
            label: '所属公司',
            field: 'companyName',
        },
        {
            type: 'RANGEPICKER',
            label: '创建时间',
            field: 'createTime',
        },
    ]

    render() {

        const {showMoreSearchForm, loading, selectedRowKeys, dataSource} = this.state;

        const buttonsStyle = {
            style: {
                marginRight: '15px',
            },
        };

        /**
         * 表格选中事件
         */
        const rowSelection = {
            selectedRowKeys: selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRowKeys: selectedRowKeys,
                    selectedRows: selectedRows,
                });
            },
        };

        return (
            <div>
                <Spin spinning={loading}>
                    <PageHeaderWrapper>
                        <Card style={{width: '100%', marginTop: '10px'}}>
                            <FilterForm formList={this.formList} filterSubmit={this.handleFilter}/>
                        </Card>

                        <Card style={{width: '100%', marginTop: '10px'}}>
                            <Tooltip title='导入账户数据！'>
                                <Button
                                    icon="import"
                                    type="primary"
                                    {...buttonsStyle}
                                    onClick={() => this.exportModal.handlerExportModal('account')}
                                >
                                    导入
                                </Button>
                            </Tooltip>
                            <Tooltip title={selectedRowKeys.length <= 0 ? '' : '当前为数据编辑状态，请先取消勾选！'}>
                                <Button
                                    icon="plus"
                                    type="primary"
                                    {...buttonsStyle}
                                    onClick={() => this.editModal.handlerEditModal('create')}
                                >
                                    新增
                                </Button>
                            </Tooltip>
                            <Tooltip title={selectedRowKeys.length == 1 ? '' : '请选中一行数据'}>
                                <Button
                                    icon="edit"
                                    type="primary"
                                    {...buttonsStyle}
                                    onClick={() => this.editModal.handlerEditModal('edit')}
                                >
                                    编辑
                                </Button>
                            </Tooltip>
                            <Tooltip title={selectedRowKeys.length > 0 && selectedRowKeys.length == 1 ? '' : '请选中一行数据'}>
                                <Popconfirm
                                    title="确定删除选中的数据吗？"
                                    onConfirm={() => this.handlerDelAccount()}
                                    okText="删除"
                                    cancelText="取消"
                                    disabled={!(selectedRowKeys.length > 0 && selectedRowKeys.length == 1)}
                                >
                                    <Button type="danger" icon="delete" {...buttonsStyle}>
                                        删除
                                    </Button>
                                </Popconfirm>
                            </Tooltip>
                        </Card>

                        <Card style={{width: '100%', marginTop: '10px', overflow: "auto"}}>
                            <Table
                                bordered
                                rowKey={data => `${data.userId}`}
                                rowSelection={rowSelection}
                                columns={this.columns}
                                dataSource={dataSource}
                                pagination={{
                                    pageSize: pagingData._pageSize,
                                    current: pagingData._current,
                                    total: pagingData._total,
                                    onChange: (page) => {
                                        pagingData._current = page;
                                        this.findPageData();
                                    },
                                    showTotal: total => `共 ${total} 条数据`,
                                    style: {
                                        float: "left"
                                    }
                                }}
                            />
                        </Card>
                        <EditAccount onRef={this.onRefEditModal} parent={this}/>
                        <ExportModal onRef={this.onRefExportModal} parent={this}/>
                    </PageHeaderWrapper>
                </Spin>
            </div>
        );
    }

    onRefEditModal = element => {
        this.editModal = element;
    };

    onRefExportModal = element => {
        this.exportModal = element;
    };

    /**
     * 表格列
     */
    columns = [
        {
            title: '用户ID',
            align: 'center',
            dataIndex: 'userId',
            key: 'userId',
        },
        {
            title: '账户名',
            align: 'center',
            dataIndex: 'userName',
            key: 'userName',
        },
        {
            title: '员工姓名',
            align: 'center',
            dataIndex: 'empName',
            key: 'empName',
        },
        {
            title: '手机号码',
            align: 'center',
            dataIndex: 'phone',
            key: 'phone',
        },
        {
            title: '创建时间',
            align: 'center',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '所属公司',
            align: 'center',
            dataIndex: 'companyName',
            key: 'companyName',
        },
        // {
        //     title: '公司logo',
        //     align: 'center',
        //     dataIndex: 'logo',
        //     key: 'logo',
        //     width: 150,
        //     height: 150,
        //     render: (text, record) => {
        //         if (text) {
        //             return <img alt={'logo'} style={{width: '100%'}} src={text} onClick={() => {
        //                 window.open(text, '_blank');
        //             }}/>
        //         }
        //     }
        // },
        {
            title: '权限',
            align: 'center',
            dataIndex: 'utypeName',
            key: 'utypeName',
        },
        {
            title: '状态',
            align: 'center',
            dataIndex: 'isenabled',
            key: 'isenabled',
            render(text) {
                const isenabled = {
                    0: '失效',
                    1: '有效',
                }
                return isenabled[text];
            }
        },
        /*{
            title: '操作',
            align: 'ceneter',
            key: 'detail',
            render: (text, record) => {
                return <a href='#' onClick={() => {
                    this.setState({
                            selectedRowKeys: record.userId,
                            selectedRows: record,
                        }
                    );
                    this.editModal.handlerEditModal('detail')
                }}>查看详情</a>
            },
        },*/
    ]
}

export default Form.create()(Account);
